﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Koala.Pro.Common;
using Koala.Pro.Core.Dto;
using Koala.Pro.Core.Models;
using Koala.Pro.Helpers;
using Koala.Pro.Services;

namespace Koala.Pro.ViewModels
{
    public partial class OuListViewModel : BaseListViewModel<OuInfo, int, OuPagedDto>
    {
        [ObservableProperty]
        private TreeViewModel<RoleAndDeptTreeNode> deptTreeModel = new TreeViewModel<RoleAndDeptTreeNode>();

        public OuListViewModel(IOuService service)
            : base(service)
        {
            ExportFields = "HandNo,Name,SortCode,Category,Address,OuterPhone,InnerPhone,Note,Creator,CreateTime,Deleted";
        }

        [RelayCommand]
        private async Task GetTree()
        {
            List<RoleAndDeptTreeNode> treeeNodeList = new List<RoleAndDeptTreeNode>();
            foreach (OuInfo item in await SecurityHelper.GetMyTopGroup(App.ViewModel.UserInfo))
            {
                if (item != null && !item.IsDeleted)
                {
                    RoleAndDeptTreeNode topnode = new RoleAndDeptTreeNode(item);
                    AddOUNodeRecursive(await BLLFactory<IOuService>.Instance.GetTreeByID(item.Id), topnode);
                    treeeNodeList.Add(topnode);
                }
            }
            DeptTreeModel.TreeItems = treeeNodeList;
            DeptTreeModel.FilteredTreeItems = new List<RoleAndDeptTreeNode>(treeeNodeList);
        }

        private List<RoleAndDeptTreeNode> AddOUNodeRecursive(List<OuInfo> children, RoleAndDeptTreeNode parentNode = null)
        {
            List<RoleAndDeptTreeNode> list = new List<RoleAndDeptTreeNode>();
            foreach (OuInfo child in children)
            {
                RoleAndDeptTreeNode roleAndDeptTreeNode = new RoleAndDeptTreeNode(child, parentNode);
                AddOUNodeRecursive(child.Children, roleAndDeptTreeNode);
                list.Add(roleAndDeptTreeNode);
            }
            return list;
        }
    }
}
